package com.atguigu.gmall.seckill.controller;

import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.seckill.service.SeckillOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * projectName: gmall
 *
 * @author: 陈鹏
 * time: 2022/10/17 21:25 星期一
 * description:秒杀下单的controller层
 */
@RestController
@RequestMapping(value = "/order/seckill")
public class SeckillOrderController {

    @Resource
    private SeckillOrderService seckillOrderService;

    /**
     * 秒杀下单: 秒杀排队
     * @param time
     * @param goodsId
     * @param num
     * @return
     */
    @GetMapping(value = "/addSeckillOrder")
    public Result addSeckillOrder(String time,String goodsId,Integer num){
        return Result.ok(seckillOrderService.addSeckillOrder(time,goodsId,num));
    }

    /**
     * 获取用户的排队信息
     * @return
     */
    @GetMapping(value = "/getUserRecord")
    public Result getUserRecord(){
        return Result.ok(seckillOrderService.getUserRecode());
    }

    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 用户主动取消订单
     * @return
     */
    @GetMapping(value = "/cancelSeckillOrder")
    public Result cancelSeckillOrder(){
        //设置用户取消的计数器
        Long increment =
                redisTemplate.opsForValue().increment("User_Cancel_Seckill_Order_Count_cp" , 1);
        if(increment > 1){
            return Result.fail();
        }
        try {
            //设置这个标识位10秒失效
            redisTemplate.expire("User_Cancel_Seckill_Order_Count_cp",10, TimeUnit.SECONDS);
            //取消秒杀订单
            seckillOrderService.cancelSeckillOrder(null);
            //返回结果
            return Result.ok();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            redisTemplate.delete("User_Cancel_Seckill_Order_Count_cp");
        }
        return Result.ok();
    }
}
